package com.hang.controller;

import com.hang.common.Result;
import com.hang.exception.MyException;
import com.hang.model.dto.request.PasswordDTO;
import com.hang.model.dto.request.UserInfoDTO;
import com.hang.model.dto.request.UserQueryModelReq;
import com.hang.model.vo.UserInfoDetailVO;
import com.hang.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

@RestController
@Api(tags = "用户管理模块")
@RequestMapping("user")
@Slf4j
public class UserController {
    @Resource
    private IUserService userService;

    @ApiOperation(value = "按条件搜索用户")
    @PostMapping("getUsersByCondition")
    public Result<Map<String,Object>> getUserInfoByCondition(@RequestBody UserQueryModelReq userQueryModelReq){
        Map<String,Object> map = userService.getUserInfoByCondition(userQueryModelReq);
        return Result.ok(map);
    }

    @ApiOperation(value = "查看用户详情")
    @GetMapping("getUserDetailById")
    public Result<UserInfoDetailVO> getUserDetailById(Long userId){
        UserInfoDetailVO userInfoDetailVO = userService.getUserDetailById(userId);
        return Result.ok(userInfoDetailVO);
    }

    @ApiOperation(value = "修改用户状态(禁用和启用状态的相互转换)")
    @GetMapping("changeStatus")
    public Result<Object> changeUserStatus(Long userId){
        Boolean open = userService.changeUserStatus(userId);
        if(open){
            return Result.ok().message("用户状态已启用");
        }else {
            return Result.ok().message("用户状态已禁用");
        }
    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("edit")
    public Result<Object> editUser(@RequestBody @Valid UserInfoDTO userInfoDTO){
        try {
            userService.updateUserInfo(userInfoDTO);
            return Result.ok().message("修改成功");
        }catch (MyException me){
            log.error(me.toString());
            return Result.fail().message(me.getMessage());
        }
    }

    @ApiOperation(value = "修改用户密码")
    @PostMapping("updatePassword")
    public Result<Object> updatePassword(@RequestBody @Valid PasswordDTO passwordDTO){
        try {
            userService.updatePassword(passwordDTO);
            return Result.ok().message("修改成功");
        }catch (MyException me){
            log.error(me.toString());
            return Result.fail().message(me.getMessage());
        }
    }

}
